﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace App.Models.Pager
{
    public static class PageLinqExtensions
    {
        public static PagedList<T> ToPagedList<T> ( this IQueryable<T> allItems,
                                                int pageIndex,
                                                int pageSize ) {
            if (pageIndex < 1)  pageIndex = 1;
            var itemIndex = (pageIndex - 1) * pageSize;
            var totalItemCount = allItems.Count();
            var pageOfItems = allItems.Skip(itemIndex).Take(pageSize);            
            return new PagedList<T>(pageOfItems, pageIndex, pageSize, totalItemCount);
        }
    }
    
    public interface IPagedList
    {
        int CurrentPageIndex { get; set; }
        int PageSize { get; set; }
        int total { get; set; }        
    }
    public class PagedList<T> : IPagedList
    {
        public List<T> list = new List<T>();
        public PagedList(IEnumerable<T> items, int pageIndex, int pageSize, int totalItemCount)
        {
            list.AddRange(items);
            total = totalItemCount;
            CurrentPageIndex = pageIndex;
            PageSize = pageSize;
        }
        public PagedList(int pageIndex, int pageSize, int totalItemCount)
        {
            total = totalItemCount;
            CurrentPageIndex = pageIndex;
            PageSize = pageSize;
        }

        public int CurrentPageIndex { get; set; }
        public int PageSize { get; set; }
        public int TotalPageCount { get { return (int)Math.Ceiling(total / (double)PageSize); } }

        public int total { get; set; }
        public List<T> rows { get { return list; } }
        public List<T> footer { get; set; }
    }

}